package org.jet.emall.security.handler;

import com.alibaba.fastjson.JSON;
import lombok.Setter;
import org.jet.emall.common.constant.CommonMapKey;
import org.jet.emall.common.restful.result.CommonResult;
import org.jet.emall.log.AdminLoginLog;
import org.jet.emall.log.LogType;
import org.jet.emall.security.model.UserDetailsModel;
import org.jet.emall.security.token.JwtUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录成功时回调处理，在这里返回给客户端的内容包括token值，用户主体信息
 * @author xiaozai
 * @version 1.0
 * @date 2020-04-07 20:12
 */
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Setter
    private JwtUtils jwtUtils;

    @AdminLoginLog(LogType.LOGIN)
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        //取出用户认证主体
        UserDetailsModel user = (UserDetailsModel) authentication.getPrincipal();

        //将用户的 id,username,roleId,roleName放进token
        Map<String, String> claims = new HashMap<>(16);
        claims.put(CommonMapKey.USER_ID_KEY,user.getId().toString());
        claims.put(CommonMapKey.USER_NAME_KEY,user.getUsername());
        claims.put(CommonMapKey.ROLE_ID_KEY,user.getRoleId().toString());
        claims.put(CommonMapKey.ROLE_NAME_KEY,user.getRoleName());
        try {

            String token = jwtUtils.createToken(claims);
            Map<String,Object> map = new HashMap<>(16);
            map.put(CommonMapKey.TOKEN_KEY,token);
            map.put(CommonMapKey.TOKEN_HEAD_KEY,jwtUtils.getTokenHead());
            map.put(CommonMapKey.TOKEN_HEADER_NAME_KEY,jwtUtils.getTokenHeaderName());
            map.put(CommonMapKey.USER_KEY,claims);
            CommonResult<Map<String, Object>> result = CommonResult.success(map, "登录成功");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(result));
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
